package controllers.administrator;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import services.AdministratorService;
import controllers.AbstractController;
import forms.RegisterForm;

@Controller
@RequestMapping("/register/admin")
public class RegisterAdministratorController extends AbstractController {

	// Constructors -----------------------------------------------------------

	public RegisterAdministratorController() {
		super();
	}

	// Services

	@Autowired
	private AdministratorService administratorService;

	// Creation ---------------------------------------------------------------

	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public ModelAndView create() {
		ModelAndView result;
	
		result = createEditModelAndView(new RegisterForm());
		
		return result;
	}

	// Edition ---------------------------------------------------------------

	@RequestMapping(value = "/save", method = RequestMethod.POST, params = "save")
	public ModelAndView save(@Valid RegisterForm registerForm, BindingResult binding) {
		ModelAndView result;

		if (binding.hasErrors()) {
			result = createEditModelAndView(registerForm);
		} else {
			try {
				
				administratorService.save(administratorService.reconstruct(registerForm));
				result = new ModelAndView("redirect:/");
			} catch (Throwable oops) {
				result = createEditModelAndView(registerForm, oops.getMessage());
			}
		}

		return result;
	}

	// Ancillary methods ------------------------------------------------------

	protected ModelAndView createEditModelAndView(RegisterForm RegisterForm) {
		ModelAndView result;

		result = createEditModelAndView(RegisterForm, null);

		return result;
	}

	protected ModelAndView createEditModelAndView(RegisterForm RegisterForm, String message) {
		ModelAndView result;

		result = new ModelAndView("register/register");
		result.addObject("authority", "ADMIN");
		result.addObject("registerForm",RegisterForm);
		result.addObject("message", message);

		return result;
	}

}
